import React from 'react';
import ReactDom from 'react-dom';

class ScrollList extends React.Component {
   constructor(props){
     super(props);
     this.state = {messages: []};
     this.container = React.createRef();
   }
   componentDidMount(){
     this.timer = setInterval(()=>{
       this.setState({
         messages: [`${this.state.messages.length}`,...this.state.messages]
       })
     },1000)
   }
   componentWillUnmount(){
     clearInterval(this.timer);
   }
   getSnapshotBeforeUpdate(){
     //在组件重新更新前获得DOM的快照
     return this.container.current. scrollHeight;
   }
   componentDidUpdate(prevProps,prevState,prevScrollHeight){
     let nextScrollTop = this.container.current.scrollTop;
     this.container.current.scrollTop = nextScrollTop + (this.container.current.scrollHeight-prevScrollHeight)
   }
   render(){
     let styleObj = {
       width: 100,
       height: 100,
       border: '1px solid red',
       overflow: 'auto'
     }
     return (
       <div style={styleObj} ref={this.container}>
        {
          this.state.messages.map((item,index)=>(
          <div key={index}>{item}</div>
          ))
        }
       </div>
     )
   }
}

ReactDom.render(
  <ScrollList/>,
  document.getElementById('root')
)
